const { pool } = require('../config/db');
const bcrypt = require('bcryptjs');

class User {
  // Get user by ID
  static async findById(id) {
    try {
      // Don't log user IDs
      
      // 确保ID是有效的
      if (!id || isNaN(parseInt(id))) {
        console.error('提供的用户ID无效');
        throw new Error('无效的用户ID');
      }
      
      const [rows] = await pool.query(
        'SELECT id, username, email, full_name, phone, address, is_admin, created_at FROM users WHERE id = ?',
        [id]
      );
      
      if (!rows || rows.length === 0) {
        // Don't log specific IDs
        console.log('未找到指定用户');
        return null;
      }
      
      // Don't log user IDs
      return rows[0];
    } catch (error) {
      console.error('查询用户失败');
      throw new Error(`获取用户失败: ${error.message}`);
    }
  }

  // Get user by username
  static async findByUsername(username) {
    try {
      const [rows] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
      return rows[0];
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Get user by email
  static async findByEmail(email) {
    try {
      const [rows] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
      return rows[0];
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Create a new user
  static async create(userData) {
    const { username, email, password, full_name, phone, address } = userData;

    try {
      // Basic validation
      if (!username || !email || !password || !full_name) {
        const missingFields = [];
        if (!username) missingFields.push('username');
        if (!email) missingFields.push('email');
        if (!password) missingFields.push('password');
        if (!full_name) missingFields.push('full_name');
        
        throw new Error(`Missing required fields: ${missingFields.join(', ')}`);
      }

      // Hash password
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);

      // Don't log user details
      console.log('Creating new user');

      const [result] = await pool.query(
        'INSERT INTO users (username, email, password, full_name, phone, address) VALUES (?, ?, ?, ?, ?, ?)',
        [username, email, hashedPassword, full_name, phone || null, address || null]
      );

      if (!result || !result.insertId) {
        throw new Error('Failed to insert new user record');
      }

      const [newUser] = await pool.query(
        'SELECT id, username, email, full_name, phone, address, is_admin, created_at FROM users WHERE id = ?',
        [result.insertId]
      );

      if (!newUser || newUser.length === 0) {
        throw new Error('User created but failed to retrieve the user data');
      }

      // Don't log user IDs
      console.log('User created successfully');
      return newUser[0];
    } catch (error) {
      // Check for duplicate entry MySQL error
      if (error.code === 'ER_DUP_ENTRY') {
        // Extract the duplicate field from the error message
        if (error.message.includes('email')) {
          throw new Error('该邮箱已被注册');
        } else if (error.message.includes('username')) {
          throw new Error('用户名已被占用');
        } else {
          throw new Error('数据已存在，注册失败');
        }
      }
      
      console.error('User creation error');
      throw new Error(`创建用户失败: ${error.message}`);
    }
  }

  // Update user
  static async update(id, userData) {
    const { full_name, phone, address } = userData;

    try {
      await pool.query(
        'UPDATE users SET full_name = ?, phone = ?, address = ? WHERE id = ?',
        [full_name, phone, address, id]
      );

      return this.findById(id);
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Admin update user
  static async adminUpdate(id, userData) {
    const { email, full_name, phone, address } = userData;

    try {
      await pool.query(
        'UPDATE users SET email = ?, full_name = ?, phone = ?, address = ? WHERE id = ?',
        [email, full_name, phone || null, address || null, id]
      );

      return this.findById(id);
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Update admin status
  static async updateAdminStatus(id, isAdmin) {
    try {
      await pool.query('UPDATE users SET is_admin = ? WHERE id = ?', [isAdmin, id]);
      return this.findById(id);
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // Change password
  static async changePassword(id, newPassword) {
    try {
      // Hash password
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(newPassword, salt);

      await pool.query('UPDATE users SET password = ? WHERE id = ?', [hashedPassword, id]);
      return true;
    } catch (error) {
      throw new Error(error.message);
    }
  }
  
  // Delete user
  static async delete(id) {
    try {
      // 验证用户存在
      const user = await this.findById(id);
      if (!user) {
        throw new Error('用户不存在');
      }
      
      // 执行删除操作
      await pool.query('DELETE FROM users WHERE id = ?', [id]);
      
      return true;
    } catch (error) {
      console.error('删除用户失败');
      throw new Error(`删除用户失败: ${error.message}`);
    }
  }
}

module.exports = User; 